package com.grantha.controllers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.grantha.util.MD5Generator;
import org.apache.log4j.Logger;

import com.grantha.util.DB;

/**
 * Servlet implementation class AddUserController
 */
@WebServlet("/ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Logger log = Logger.getLogger(this.getClass());
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
				
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		HttpSession session=request.getSession();
		PrintWriter out = response.getWriter();
		
		log.info("Servlet Stated");
		//coding start 
		
		String username = (String) session.getAttribute("CurrentUserName");
				//((String)CurrentUserName);
		String currentpassword = MD5Generator.md5(request.getParameter("pass1")); 
		String newpassword = MD5Generator.md5(request.getParameter("pass2"));
		
		log.info("user="+username);
		log.info("Cpass="+currentpassword);
		log.info("Npass="+newpassword);
	
		
		
		try {
			
			DB.update("update users set password=? where (password=? and username=?)",newpassword,currentpassword,username);
			
			out.print("success");
			log.info("success");
		} catch (Exception e) {
			out.print("error");
			log.error("Error");
		}
		
		//coding ends
		
		out.close();
		log.info("Servlet end");
	}

}
